package com.sbr.seb.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sbr.seb.entity.TomcatApplication;
import com.sbr.seb.entity.server.Tomcat;
import com.sbr.seb.exception.SebException;
import com.sbr.seb.reader.ManagerListReader;
import com.sbr.seb.service.TomcatManagerService;
import com.sbr.seb.util.UrlConnector;

public class TomcatManagerServiceImpl implements TomcatManagerService {

	private static final Logger logger = LoggerFactory.getLogger(TomcatManagerServiceImpl.class);

	private UrlConnector connector;
	
	public TomcatManagerServiceImpl() {
		connector = new UrlConnector();
	}
	
	@Override
	public void startApplication() {

	}

	@Override
	public void stopApplication() {

	}

	@Override
	public void restartApplication() {

	}

	@Override
	public Collection<TomcatApplication> getApplicationsList() {
		Tomcat tomcat = new Tomcat();
		tomcat.setHost("traversaine.dsi.damgm.i2");
		connector.setLogin(tomcat.getLogin());
		connector.setPassword(tomcat.getPassword());

		BufferedReader in = null;
		try {
			in = connector.getReader(tomcat.getManagerListUrl());
		} catch (IOException e) {
			logger.error("",e);
			throw new SebException(e);
		}

		ManagerListReader reader = new ManagerListReader();
		Collection<TomcatApplication> applicationList = null;
		try {
			applicationList = reader.read(in);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("",e);
				}
			}
		}

		return applicationList;

	}
	
	@Override
	public Collection<TomcatApplication> getApplicationsList(Tomcat tomcat) {
		connector.setLogin(tomcat.getLogin());
		connector.setPassword(tomcat.getPassword());

		BufferedReader in = null;
		try {
			in = connector.getReader(tomcat.getManagerListUrl());
		} catch (IOException e) {
			logger.error("",e);
			throw new SebException(e);
		}

		ManagerListReader reader = new ManagerListReader();
		Collection<TomcatApplication> applicationList = null;
		try {
			applicationList = reader.read(in);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("",e);
				}
			}
		}

		return applicationList;

	}
}
